﻿using System;
using System.Collections.Generic;
using System.Data;
using ContractManager.BLL.Business;
using ContractManager.Common.Class;
using ContractManager.Common.FormBase;
using System.Windows.Forms;
using ContractManager.Entity;
using DevExpress.XtraEditors;

namespace ContractManager.Lists.Contracts
{
    public partial class FrmPlanRevenueDetail : XtraFormBase
    {
        #region "Private Variable"
        
        public bool SaveClose;
        public bool SaveNew;
        public bool OnlyView;
        public int MasterId;

        #endregion

        #region "Form Construction"
        public FrmPlanRevenueDetail()
        {
            InitializeComponent();
        }
        #endregion

        #region "Private Method"

        private void BlankForm()
        {
           
            this.ResetControls();
            //txtPlanRevNo.Properties.ReadOnly = MasterId > 0;
            grdDetail.DataSource = null;
            grdDetail.DataSource = ClsPlanRevenues.ListDetail(0);
        }

        private void LoadLookupData()
        {
            branchSearchLookUpEdit.DataSource = ClsMemberBranch.SelectAll();
            branchSearchLookUpEdit.DisplayMember = "MbName";
            branchSearchLookUpEdit.ValueMember = "MbID";

            workSearchLookUpEdit.DataSource = ClsWorkType.SelectAll();
            workSearchLookUpEdit.DisplayMember = "WorkName";
            workSearchLookUpEdit.ValueMember = "WorkId";
        }

        private void GetDetail()
        {
            var detail = ClsPlanRevenues.SelectByPk(MasterId);
            if (detail != null)
            {
                txtPlanRevNo.EditValue = String.Format("{0}",detail.PlanRevNo);
                txtPlanRevDate.EditValue = detail.PlanRevDate;
                txtPlanRevContent.EditValue = detail.PlanRevContent;
                txtPlanRevDescription.EditValue = detail.PlanRevDescription;
                txtCustomField1.EditValue = String.Format("{0}", detail.CustomField1);
                txtCustomField2.EditValue = String.Format("{0}", detail.CustomField2);
                txtCustomField3.EditValue = String.Format("{0}", detail.CustomField3);
                txtCustomField4.EditValue = String.Format("{0}", detail.CustomField4);
                txtCustomField5.EditValue = String.Format("{0}", detail.CustomField5);
                txtCustomField6.EditValue = String.Format("{0}", detail.CustomField6);
                txtCustomField7.EditValue = String.Format("{0}", detail.CustomField7);
                txtCustomField8.EditValue = String.Format("{0}", detail.CustomField8);
                txtCustomField9.EditValue = String.Format("{0}", detail.CustomField9);
                txtCustomField10.EditValue = String.Format("{0}", detail.CustomField10);

                grdDetail.DataSource = null;
                grdDetail.DataSource = ClsPlanRevenues.ListDetail(MasterId);

                if (this.LstLockDate.Contains(Convert.ToDateTime(detail.PlanRevDate).Date))
                {
                    OnlyView = true;
                    btnSaveNew.Enabled = !OnlyView;
                    btnSave.Enabled = !OnlyView;
                    btnSaveClose.Enabled = !OnlyView;
                    btnDelete.Enabled = !OnlyView && this.AllowDelete;
                    btnDesign.Enabled = !OnlyView;
                }
            } 
  

        }

        private void DoSave()
        {
            grdDetail.EmbeddedNavigator.Buttons.DoClick(grdDetail.EmbeddedNavigator.Buttons.EndEdit);

            #region "Variable"
            
            DataTable dtSource = (DataTable)grdDetail.DataSource;

            #endregion

            #region "Check Condition"
            //if (!FormIsNotValidate)
            //{
            //    if (!dxValidationProvider.Validate())
            //    {
            //        XtraMessageBox.Show(
            //                    "Vui lòng nhập đầy đủ thông tin trước khi lưu",
            //                    "Thông báo",
            //                    MessageBoxButtons.OK,
            //                    MessageBoxIcon.Error);
            //        txtCode.SelectAll();
            //        txtCode.Focus();
            //        return;
            //    }
            //}
            if (LstLockDate.Contains(txtPlanRevDate.DateTime.Date))
            {
                XtraMessageBox.Show(
                                "Ngày chứng từ đã bị khoá sổ. Vui lòng nhập ngày khác",
                                "Thông báo",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
                txtPlanRevDate.SelectAll();
                txtPlanRevDate.Focus();
                return;
            }
            if (dtSource.Rows.Count == 0)
            {
                XtraMessageBox.Show(
                            "Số lượng công việc trong hợp đồng phải >0.",
                            "Thông báo",
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Error);
                txtPlanRevNo.SelectAll();
                txtPlanRevNo.Focus();
                return;
            }
            #endregion

            var item = MasterId <= 0 ? new PlanRevenues() : ClsPlanRevenues.SelectByPk(MasterId);
            item.PlanRevNo = String.Format("{0}", txtPlanRevNo.EditValue);
            item.PlanRevDate = txtPlanRevDate.DateTime;
            item.PlanRevContent = String.Format("{0}", txtPlanRevContent.EditValue); 
            item.PlanRevDescription = String.Format("{0}", txtPlanRevDescription.EditValue);
            
            item.CustomField1 = String.Format("{0}", txtCustomField1.EditValue);
            item.CustomField2 = String.Format("{0}", txtCustomField2.EditValue);
            item.CustomField3 = String.Format("{0}", txtCustomField3.EditValue);
            item.CustomField4 = String.Format("{0}", txtCustomField4.EditValue);
            item.CustomField5 = String.Format("{0}", txtCustomField5.EditValue);
            item.CustomField6 = String.Format("{0}", txtCustomField6.EditValue);
            item.CustomField7 = String.Format("{0}", txtCustomField7.EditValue);
            item.CustomField8 = String.Format("{0}", txtCustomField8.EditValue);
            item.CustomField9 = String.Format("{0}", txtCustomField9.EditValue);
            item.CustomField10 = String.Format("{0}", txtCustomField10.EditValue);

            item.FormId = FormNo;
            item.VoucherCate = VoucherCate;

            item.ListAdd = GetListAdd(dtSource.GetChanges(DataRowState.Added));
            item.ListUpdate = GetListUpdate(dtSource.GetChanges(DataRowState.Modified));
            item.ListDelete = GetListDelete(dtSource.GetChanges(DataRowState.Deleted));
            try
            {
                if (MasterId > 0)
                {
                    item.UpdateBy = ClsVariable.EmployeeId;
                    item.UpdateDate = DateTime.Now;
                    ClsPlanRevenues.Update(item); 
                }
                else
                {
                    item.CreateBy = ClsVariable.EmployeeId;
                    item.CreateDate = DateTime.Now;
                    ClsPlanRevenues.Insert(item);
                    MasterId = item.PlanRevId;
                }

                dtSource.AcceptChanges();
                grdDetail.DataSource = ClsPlanRevenues.ListDetail(MasterId);

                if (SaveNew)
                {
                    MasterId = 0;
                    BlankForm();
                    txtPlanRevNo.Focus();
                    
                }
                else if (SaveClose)
                {
                    Close();
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(
                    String.Format("Có lỗi xảy ra trong quá trình cập nhật dữ liệu. {0}", ex.Message),
                    "Thông báo",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
            }
        }

        private void DoDelete()
        {
            if (MasterId <= 0) return;
            
            try
            {
                if (
                        XtraMessageBox.Show(
                                        "Bạn có muốn xóa bản ghi này không?",
                                        "Thông báo",
                                        MessageBoxButtons.YesNo,
                                        MessageBoxIcon.Question) == DialogResult.No) return;
                ClsRevenues.DeleteByPk(MasterId);
                Close();
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(
                       "Có lỗi xảy ra trong quá trình xóa dữ liệu. " + ex.Message,
                       "Thông báo",
                       MessageBoxButtons.OK,
                       MessageBoxIcon.Error);
            }
        }

        private List<PlanRevenueDetails> GetListAdd(DataTable dataTable)
        {
            List<PlanRevenueDetails> list = new List<PlanRevenueDetails>();
            if (dataTable != null && dataTable.Rows.Count > 0)
            {
                dataTable.BeginLoadData();
                foreach (DataRow row in dataTable.Rows)
                {
                    PlanRevenueDetails item = new PlanRevenueDetails();
                    item.PlanRevDetId = 0;
                    item.MbID = Convert.ToInt32(row["MbID"]);
                    item.WorkId = Convert.ToInt32(row["WorkId"]);
                    item.PlanRevDetDescription = String.Format("{0}", row["PlanRevDetDescription"]);
                    item.PlanRevDetAmount = row["PlanRevDetAmount"] == DBNull.Value ? 0 : Convert.ToDouble(row["PlanRevDetAmount"]);

                    item.CustomField1 = String.Format("{0}", row["CustomField1"]);
                    item.CustomField2 = String.Format("{0}", row["CustomField2"]);
                    item.CustomField3 = String.Format("{0}", row["CustomField3"]);
                    item.CustomField4 = String.Format("{0}", row["CustomField4"]);
                    item.CustomField5 = String.Format("{0}", row["CustomField5"]);

                    list.Add(item);
                    
                }
                dataTable.EndLoadData();
            }
            return list;
        }

        private List<PlanRevenueDetails> GetListUpdate(DataTable dataTable)
        {
            List<PlanRevenueDetails> list = new List<PlanRevenueDetails>();
            if (dataTable != null && dataTable.Rows.Count > 0)
            {
                dataTable.BeginLoadData();
                foreach (DataRow row in dataTable.Rows)
                {
                    PlanRevenueDetails item = new PlanRevenueDetails();
                    item.PlanRevDetId = Convert.ToInt32(row["PlanRevDetId"]);
                    item.MbID = Convert.ToInt32(row["MbID"]);
                    item.WorkId = Convert.ToInt32(row["WorkId"]);
                    item.PlanRevDetDescription = String.Format("{0}", row["PlanRevDetDescription"]);
                    item.PlanRevDetAmount = row["PlanRevDetAmount"] == DBNull.Value ? 0 : Convert.ToDouble(row["PlanRevDetAmount"]);

                    item.CustomField1 = String.Format("{0}", row["CustomField1"]);
                    item.CustomField2 = String.Format("{0}", row["CustomField2"]);
                    item.CustomField3 = String.Format("{0}", row["CustomField3"]);
                    item.CustomField4 = String.Format("{0}", row["CustomField4"]);
                    item.CustomField5 = String.Format("{0}", row["CustomField5"]);

                    list.Add(item);

                }
                dataTable.EndLoadData();
            }
            return list;
        }

        private List<PlanRevenueDetails> GetListDelete(DataTable dataTable)
        {
            List<PlanRevenueDetails> list = new List<PlanRevenueDetails>();
            if (dataTable != null && dataTable.Rows.Count > 0)
            {
                dataTable.BeginLoadData();
                foreach (DataRow row in dataTable.Rows)
                {
                    PlanRevenueDetails item = new PlanRevenueDetails();
                    item.PlanRevDetId = Convert.ToInt32(row["PlanRevDetId", DataRowVersion.Original]);
                    list.Add(item);

                }
                dataTable.EndLoadData();
            }
            return list;
        }

        

        #endregion

        #region "Form Event"
        private void FrmPlanRevenueDetailLoad(object sender, EventArgs e)
        {
            BlankForm();
            LoadLookupData();
            if (MasterId > 0) GetDetail();
            btnSaveNew.Enabled = !OnlyView;
            btnSave.Enabled = !OnlyView;
            btnSaveClose.Enabled = !OnlyView;
            btnDelete.Enabled = !OnlyView;
            btnDesign.Enabled = !OnlyView;
            if (!String.IsNullOrEmpty(FormXtraLayoutTemplate))
            {
                var fileLayout = ClsVariable.GetRestoreLayoutFullPath(FormXtraLayoutTemplate);
                layoutControl.RestoreLayoutFromXml(fileLayout);
            }
            if (!String.IsNullOrEmpty(FormXtraGridLayoutTemplate))
            {
                var filePath = ClsVariable.GetRestoreLayoutFullPath(FormXtraGridLayoutTemplate);
                grvDetail.RestoreLayoutFromXml(filePath, DevExpress.Utils.OptionsLayoutBase.FullLayout);
            }
        }
        #endregion

        #region "Toolbar Event"
        private void TbMenuItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            switch (e.Item.Name)
            {
                case "btnSave":
                    DoSave();
                    break;
                case "btnSaveNew"://Lưu và thêm mới
                    SaveNew = true;
                    DoSave();
                    break;
                case "btnSaveClose"://Lưu và đóng
                    SaveClose = true;
                    DoSave();
                    break;
                case "btnDelete":
                    DoDelete();
                    break;
                case "btnDesign":
                    ClsVariable.ShowDesignXtraGrid(grdDetail);
                    break;
                case "btnRefresh"://Nạp lại danh mục
                    break;
                case "btnHistory"://History
                    break;
                case "btnClose":
                    Close();
                    break;
            }
        }
        #endregion

        

        
    }
}
